import { h, onMounted, reactive, ref, toRaw, computed, nextTick } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import InvoicingForm from "../InvoicingForm.vue";
import { message } from "@/utils/message";
import Details from "../detail.vue";
import InvDetails from "../invoicingDetail.vue";
import dayjs from 'dayjs';
import {
  taskListApi,
  taskStoreApi,
  taskUpdateApi,
  taskDeleteApi,
  taskShowApi,
  taskUpdateStatusApi,
  bulkUpdateStatusApi
} from "@/api/taskApi";
import {
  projectSelectApi
} from "@/api/projectApi";
import { userSelectApi } from "@/api/user"
import { ElMessageBox } from 'element-plus'
import { noticeStoreApi } from "@/api/noticeApi";
import {
  invoiceStoreApi
} from "@/api/invoiceApi";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 100,
    listType: "assignedToMe",
    projectId: null,
    projectSelect: [],
    projectName: null,
    projectNo: null,
    projectType: null,
    electControl: null,
    consignType: null,
    receiptFull: null,
    keyword: null,
    isDelive: null
  });
  const formRef = ref();
  const InvoicingFormRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 100,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });
  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand",
      fixed: "left",
      width: 36
    },
    {
      label: "项目名称",
      prop: "projectName",
      fixed: "left",
      width: 200
    },
    {
      label: "项目编码",
      prop: "projectNo",
      sortable: true,
      minWidth: 150
    },
    {
      label: "项目类型",
      prop: "projectTypeName",
      minWidth: 120
    },

    {
      label: "任务阶段",
      prop: "taskTypeName",
      minWidth: 120,
      slot: "taskTypeName"
    },
    // {
    //   label: "可执行数",
    //   prop: "execTaskCount",
    //   minWidth: 100,
    //   formatter:(row: any)=> {
    //     return row.execTaskCount || '--'
    //   },
    // },
    // {
    //   label: "待执行阶段",
    //   prop: "nextTaskTypeName",
    //   minWidth: 190,
    //   formatter:(row: any)=> {
    //     return row.nextTaskTypeName || '--'
    //   },
    // },
    // {
    //   label: "进行阶段",
    //   prop: "taskTypeName",
    //   minWidth: 160,
    //   // formatter:(row: any)=> {
    //   //   return row.taskTypeName || '--'
    //   // },
    // },
    {
      label: "货款类型",
      prop: "consignType",
      formatter:(row: any)=> {
        return row.consignType === 1? '发货款' : '到货款';
      },
      minWidth: 90
    },
    {
      label: "是否电控",
      prop: "electControl",
      formatter:(row: any)=> {
        return row.electControl === 1? '是' : '否';
      },
      minWidth: 90
    },
    {
      label: "收款标识",
      prop: "receiptFull",
      slot: "receiptFull",
      minWidth: 100,
    },
    {
      label: "交付状态",
      prop: "isDelive",
      slot: "isDelive",
      minWidth: 110,
    },
    {
      label: "计划日期",
      prop: "planStartDate",
      formatter:(row: any)=> {
        let s = row.planStartDate;
        let e = row.planEndDate;
        return s + ' 至 ' + e
      },
      minWidth: 200
    },
    {
      label: "负责人",
      prop: "principalUser.name",
      minWidth: 100
    },
    {
      label: "项目附件",
      prop: "attachment",
      slot: "attachment",
      minWidth: 100
    },
    {
      label: "工作日(天)",
      prop: "effectDay",
      minWidth: 100
    },
    {
      label: "剩余时间(天)",
      prop: "surplusDate",
      minWidth: 110
    },
    {
      label: "创建时间",
      prop: "createdAt",
      minWidth: 160
    },
    {
      label: "更新时间",
      prop: "updatedAt",
      minWidth: 160
    },
    // {
    //   label: "操作",
    //   fixed: "right",
    //   slot: "operation",
    //   width: 120
    // }
  ];
  const columnsTask: TableColumnList = [
    // {type: "selection", slot: "selection", width: 55},
    {
      label: "审核阶段",
      prop: "taskTypeName",
      width: 170,
      fixed: "left",
    },
    {
      label: "状态",
      prop: "status",
      slot: "status",
      width: 100
    },
    {
      label: "计划日期",
      prop: "planStartDate",
      formatter:(row: any)=> {
        let s = row.planStartDate;
        // if(row.planStartDate) {
        //   s = dayjs(row.planStartDate).format('YYYY-MM-DD HH:mm');
        // }
        let e = row.planEndDate;
        // if(row.planEndDate) {
        //   e = dayjs(row.planEndDate).format('YYYY-MM-DD HH:mm');
        // }
        return s + ' 至 ' + e
      },
      // slot: "planStartDate",
      width: 280
    },
    {
      label: "实际日期",
      prop: "realEndDate",
      formatter:(row: any)=> {
        let e = row.realEndDate??"--";
        let s = row.realStartDate??"--";
        return s + ' 至 '+ e
      },
      slot: "realEndDate",
      width: 280
    },
    {
      label: "完成比例(%)",
      prop: "completeRate",
      width: 110,
      formatter:(row: any)=> {
        let str: any = row.completeRate;
        if(row.childrens && row.childrens.length > 0) {
          str = '--'
        }
        return str
      },
    },
    {
      label: "收款比例(%)",
      prop: "receiptRatio",
      minWidth: 110,
      formatter:(row: any)=> {
        let str: any = '--';
        if(row.taskType === 1020000 || row.taskType === 1070000 || row.taskType === 1090000 || row.taskType === 1120000 || row.taskType === 1130000) {
          str = row.receiptRatio
        }
        return str
      },
    },
    {
      label: "附件",
      prop: "attachment",
      width: 100,
      slot: "attachment"
    },
    {
      label: "预计小时",
      prop: "expectHour",
      width: 100,
      formatter:(row: any)=> {
        return row.expectHour ?? '--'
      },
    },
    // {
    //   label: "优先级",
    //   prop: "priority",
    //   width: 100,
    //   formatter:(row: any)=> {
    //     return row.priority ?? '--'
    //   },
    // },
    {
      label: "指派给用户",
      prop: "assignedTo",
      width: 150,
      slot: "assignedTo"
    },
    {
      label: "抄送给用户",
      prop: "assignedExtraTo",
      width: 150,
      slot: "assignedExtraTo"
    },
    // {
    //   label: "创建时间",
    //   prop: "createdAt"
    // },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 210
    }
  ];
  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    let params = {
      page: form.page,
      perPage: form.perPage,
      projectType: form.projectType,
      listType: form.listType,
      projectName: form.projectName,
      projectNo: form.projectNo,
      electControl: form.electControl,
      consignType: form.consignType,
      receiptFull: form.receiptFull,
      keyword: form.keyword,
      isDelive: form.isDelive
    }
    const res: any = await taskListApi(toRaw(params));
    if(res?.result?.list && res?.result?.list.length) {
      for (let item of res?.result?.list) {
        for (let row of item.taskList) {
          row.checkbox = false

        }
      }
    }
    // if(res?.result?.list && res?.result?.list.length > 0) {
    //   let list = res?.result?.list;

    //   for (let item of list) {
    //     for (let task of item.taskList) {
    //       task.showPrevTask = false;
    //       task.showReceive = false;
    //       for (let child of task.childrens) {
    //         child.showPrevTask = false;
    //         child.showReceive = false;
    //       }
    //     }
    //   }
    //   for (let item of list) {
    //     let lastStatus = item.taskList.findLastIndex(item => item.status === 3);


    //     for (let i = 1; i < item.taskList.length; i++) {

    //       let falg = item.taskList[i].taskType === 1020000 || item.taskList[i].taskType === 1070000 || item.taskList[i].taskType === 1090000;
    //       // 判断跳过或最后一次完成，下一阶段显示接收
    //       if((falg && item.taskList[i].status === 2) || lastStatus < item.taskList.length -1 ) {
    //         item.taskList[lastStatus+1].showReceive = true;
    //         if(falg && item.taskList[i].status === 2){
    //           if(item.taskList[lastStatus+2].taskType === 1030000) {
    //             item.taskList[lastStatus+3].showReceive = true;
    //           }
    //         } else {
    //           if(item.taskList[lastStatus+1].taskType === 1030000) {
    //             item.taskList[lastStatus+2].showReceive = true;
    //           }
    //         }

    //         // 判断最后一次完成，下一阶段是否挂起跳过，是的话就+2显示接收
    //         if(item.taskList[lastStatus+1].status === 2) {
    //           item.taskList[lastStatus+2].showReceive = true;
    //         }
    //       }
    //       if(item.taskList[i].childrens && item.taskList[i].childrens.length > 0) {
    //         let child = item.taskList[i].childrens
    //         let childOne = []
    //         let childTwo = []
    //         // 一条线是做判断
    //         if(item.taskList[i].childrens.length === 3) {
    //           childOne = item.taskList[i].childrens;
    //           let childLastStatus = childOne.findLastIndex(item => item.status === 3);
    //           // 判断任务的上一步是否完成或挂起，显示接收按钮
    //           if(lastStatus < child.length -1 && item.taskList[i-1].status === 3 || item.taskList[i-1].status === 2) {
    //             child[childLastStatus+1].showReceive = true;
    //           }
    //         }
    //         // 两条线判断
    //         if(item.taskList[i].childrens.length === 6) {
    //           childOne = [item.taskList[i].childrens[0], item.taskList[i].childrens[1], item.taskList[i].childrens[2]];
    //           childTwo = [item.taskList[i].childrens[3], item.taskList[i].childrens[4], item.taskList[i].childrens[5]];
    //           let childLastStatusOne = childOne.findLastIndex(item => item.status === 3);
    //           let childLastStatusTwo = childTwo.findLastIndex(item => item.status === 3);
    //           // 判断任务的上一步是否完成或挂起，显示接收按钮
    //           if(lastStatus < child.length -1 && item.taskList[i-1].status === 3 || item.taskList[i-1].status === 2) {
    //             child[childLastStatusOne+1].showReceive = true;
    //             if(childLastStatusTwo < 2) {
    //               child[childLastStatusTwo+4].showReceive = true;
    //             }

    //           }
    //         }

    //         for (let j = 0; j < child.length; j++) {
    //           if(child[j].status === 1) {
    //             child[j].showPrevTask = true;
    //           }
    //         }
    //       }

    //       // 判断任务的上一步是否完成或挂起，显示接收按钮
    //       if( (falg && item.taskList[i].status === 2) || item.taskList[i].status === 1) {
    //         if(item.taskList[i].childrens.length === 0){
    //           item.taskList[i].showPrevTask = true;
    //         }
    //       }

    //     }

    //   }
    // }
    dataList.value = res?.result?.list;
    pagination.total = res?.result?.total;
    pagination.pageSize = res?.result?.perPage*1;
    if(pagination.pageSize === 0) {
      pagination.pageSize = 10
    }
    // pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.page = 1;
    form.projectId = null;
    form.projectType = null;

    form.projectName = null;
    form.projectNo = null;
    form.electControl = null;
    form.consignType = null;
    form.receiptFull = null;
    form.keyword = null;
    form.isDelive = null;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  const formInline = ref();
  let tableData = ref([])
  async function openDialog(title = "创建任务", row?: FormItemProps, propsRow?: FormItemProps) {
    // const project: any = await projectSelectApi({type: 'all'});
    if (`${title}` == "创建任务") {
      formInline.value = {
        title: "创建任务",
        // projectSelect: project?.result ?? [],
        userSelect: userSelect.value.result
      };
    } else {
      if(title === '批量执行') {

        if(tableData.value.length <= 0) {
          message(`请选择选中表格中的数据`, {
            type: "warning"
          });
          return
        }
        const allValuesSame = tableData.value.every(item => item.checkbox === false);

        if(allValuesSame) {
          message(`请选择选中表格中的数据`, {
            type: "warning"
          });
          return
        }
        let flag = false;
        for (let item of tableData.value) {
          if(item.checkbox && item.status !== 3) {
            if(item.taskType === 1020000 || item.taskType === 1070000 || item.taskType === 1090000 || item.taskType === 1120000 || item.taskType === 1130000) {
              flag = true
            }
          }

        }
        formInline.value = {
          title: title,
          status: 3,
          flag: flag,
          completeRate: 100,
          receiptRatio: 100
        }
      } else {
        const res: any = await taskShowApi({ taskId: row?.taskId });
        formInline.value = {
          title: title,
          userSelect: userSelect.value?.result,
          // projectSelect: project?.result ?? [],
          taskId: res?.result?.taskId ?? "",
          taskType: res?.result?.taskType ?? "",
          projectName: res?.result?.project?.projectName ?? "",
          projectNo: res?.result?.project?.projectNo ?? "",
          projectId: res?.result?.projectId ?? "",
          taskTypeName: row.taskTypeName ?? "",
          receiptRatio: row.receiptRatio
        };
        if(title === '执行任务'){
          formInline.value.currentTaskTypeName = res?.result?.currentTaskTypeName
          formInline.value.currentTaskType = res?.result?.currentTaskType
          formInline.value.completeRate = row.completeRate
          formInline.value.beforeCompleteRate = row.completeRate
          formInline.value.beforeReceiptRatio = row.receiptRatio
          formInline.value.status = row.status
          formInline.value.statusFlag = row.status ===3?true:false
          formInline.value.receiptFull = propsRow?.receiptFull;
          formInline.value.fn = onSearch;
          let attachment = []
          if(res?.result?.attachment && res?.result?.attachment.length > 0) {
            for (let item of res?.result?.attachment) {
              attachment.push(item.storageAddr)
            }
          }

          formInline.value.attachment = attachment
          formInline.value.remarks = res?.result?.operateLog[0].remarks

        }
        if(title === '日志'){
          if(res?.result?.operateLog) {
            for (let item of res?.result?.operateLog) {
              item.attachment = JSON.parse(item.attachment)
            }
            formInline.value.record = res?.result?.operateLog
          }

        }
      }

    }
    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      width: title === '日志'?"80%":"44%",
      hideFooter: title === '日志' || title === '执行任务'?true:false,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;


        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "创建任务" || title === "编辑任务") {
              let hasMultiUser = 0
              if(curData.assignedTo.length > 1) {
                hasMultiUser = 1
              }
              const params = {
              	parentId: curData.parentId,
              	projectId: curData.projectId,
              	taskType: curData.taskType,
              	hasMultiUser: hasMultiUser,
              	assignedTo: curData.assignedTo,
                planStartDate: (curData.rangePlanDate[0].match(/:/g) || []).length ===1?curData.rangePlanDate[0]+':00':curData.rangePlanDate[0],
                planEndDate: (curData.rangePlanDate[1].match(/:/g) || []).length ===1?curData.rangePlanDate[1]+':00':curData.rangePlanDate[1],
                priority: curData.priority,
                expectHour: curData.expectHour,
                description: curData.description,
                keyword: curData.keyword,
                attachment: curData.attachment,
                assignedExtraTo: curData.assignedExtraTo,
                status: curData.status,
                completeRate: curData.completeRate,
              }
              if (title === "创建任务") {
                taskStoreApi(params)
                  .then((res: any) => {
                    if(res?.code ===200) {
                      chores();
                    }

                  })
                  .catch(error => {
                    message(error.response.data.msg ?? "操作失败,请联系管理员", {
                      type: "error"
                    });
                  });
              } else {
                taskUpdateApi(params).then((res: any) => {
                  if(res?.code ===200) {
                    chores();
                  }
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
              }
            } else if(title === '执行任务') {
              if(row.status === 3) {
                message("该阶段已完成，请勿重复操作", {
                  type: "error"
                });
                return
              }
              if(curData.status !== 1 && !curData.remarks) {
                message("请输入备注!", {
                  type: "error"
                });
                return
              }
              // if(curData.attachment.length === 0 && curData.status === 3){
              //   message("请上传附件!", {
              //     type: "error"
              //   });
              //   return
              // }

              if(curData.taskType === 1100000 && curData.attachment.length === 0 && curData.status === 3) {
                message("请上传附件!", {
                  type: "error"
                });
                return
              }
              let params = {
                taskId: curData.taskId,
                taskType: curData.taskType,
                projectId: curData.projectId,
                status: curData.status,
                remarks: curData.remarks,
                attachment: curData.attachment,
                completeRate: curData.completeRate ? curData.completeRate : 0,
                receiptRatio: curData.receiptRatio,
                receiptFull: curData.receiptFull
              }
              taskUpdateStatusApi(cleanEmptyData(params)).then((res: any)=> {
                if(res?.code ===200) {
                  message(`操作成功`, {
                    type: "success"
                  });
                  done();
                  onSearch();
                }
              }).catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else if(title === '批量执行') {
              let checkbox = []
              for (let item of tableData.value) {
                if(item.checkbox) {
                  checkbox.push(item)
                }
              }
              if(!curData.remarks) {
                message("请输入备注", {
                  type: "warning"
                });
                return
              }

              let params = {
                lastTaskId: checkbox[checkbox.length-1].taskId,
                projectId: checkbox[checkbox.length-1].projectId,
                status: 3,
                remarks: curData.remarks,
                attachment: curData.attachment,
                completeRate: 100,
                receiptRatio: 100,
                taskType: checkbox[checkbox.length-1].taskType
              }
              bulkUpdateStatusApi(params).then((res: any)=> {
                if(res?.code ===200) {
                  message(`操作成功`, {
                    type: "success"
                  });
                  done();
                  onSearch();
                }
              }).catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              done();
            }
          }
        });
      }
    });
  }

  const userSelect = ref()
  onMounted(async () => {
    onSearch();
    userSelect.value = await userSelectApi()
  });

  function handleDelete(row) {
    taskDeleteApi({ taskId: row.taskId }).then(() => {
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }

  function onDetail(row) {
    taskShowApi({ taskId: row.taskId }).then((res: any) => {
      if(res?.code ===200) {
        let params = {
          taskTypeName: row.taskTypeName
        }
        addDialog({
          top: "5vh",
          width: "600px",
          title: "详情",
          hideFooter: true,
          contentRenderer: () => h(Details),
          props: {
            info: {...res?.result, ...params} ?? {}
          }
        });
      }

    });
  }
  function receiveChange(row) {
    ElMessageBox.confirm('接收任务后无法回退，是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      let params = {
        taskId: row.taskId,
        status: 1,
        completeRate: 0,
        projectId: row.projectId,
        taskType: row.taskType,
        receiptRatio: 0,
        receiptFull: 0
      }
      taskUpdateStatusApi(params).then((res: any)=> {
        if(res?.code ===200) {
          message("操作成功!", {
            type: "success"
          });
          onSearch();
        }
      }).catch(error => {
        message(error.response.data.msg ?? "操作失败,请联系管理员", {
          type: "error"
        });
      });
    })
  }

  // 开票弹窗
  function openInvoicing (row: any) {
    if(row && row.invoice) {
      message(`已开票，请勿重复操作!`, {
        type: "error"
      });
      return
    }
    addDialog({
      top: "5vh",
      width: "500px",
      title: "开票",
      hideFooter: false,
      props: {
        formInline: row
      },
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(InvoicingForm, { ref: InvoicingFormRef }),
      beforeSure: (done, { options }) => {
        const FormRef = InvoicingFormRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`开票成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            const params = {
              taskIds: [curData.taskId],
              projectId: curData.projectId,
              // isVat: curData.isVat,
              title: curData.title,
              // content: curData.content,
              amount: curData.amount.toFixed(2),
              // taxNo: curData.taxNo,
              // tax: curData.tax.toFixed(2),
              // companyName: curData.companyName,
              // companyAddress: curData.companyAddress,
              // telephone: curData.telephone,
              // bankName: curData.bankName,
              // bankAccount: curData.bankAccount,
            }
            invoiceStoreApi(params).then((res: any) => {
              if(res?.code === 200) {
                chores()
              }
            }).catch(error => {
              message(error.response.data.msg ?? "操作失败,请联系管理员", {
                type: "error"
              });
            });
          }
        })
      }

    });
  }
  function invoicingDetail(row, propsRow) {
    let project = {
      projectName: propsRow.projectName,
      projectNo: propsRow.projectNo,
    }
    addDialog({
      top: "5vh",
      width: "600px",
      title: "开票详情",
      hideFooter: true,
      contentRenderer: () => h(InvDetails),
      props: {
        info: {...row, ...project}
      }
    });
  }
  const multipleTableRef = ref()
  const selectionData = ref([])
  async function handleSelectionChange (val) {
    let arr = []
    if(!val) {
      return
    }

  }

  return {
    form,
    isShow,
    loading,
    columns,
    columnsTask,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    userSelect,
    onDetail,
    receiveChange,
    openInvoicing,
    invoicingDetail,
    handleSelectionChange,
    multipleTableRef,
    tableData
  };
}
